package com.bing.common.model;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.bing.common.constant.CommonConstant;
import lombok.Getter;
import lombok.Setter;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;

/**
 * @Description TODO
 * @Author Bing
 * @Date 2024/10/14 13:58
 */
@Getter
@Setter
public class PageResult<T> extends BaseResult {
    // 总记录数
    private Long total;

    /** 列表数据 */
    private List<T> rows;

    private PageResult(int code, String msg, Long total,List<T> rows){
        super(code, msg);
        this.total = total;
        this.rows = rows;
    }

    public static <T> PageResult<T> empty(){
        return getInstance(CommonConstant.DEFAULT_SUCCESS_CODE, null, 0L, new ArrayList<>(0));
    }

    public static <T> PageResult<T> success(IPage<T> page){
        return success(page.getTotal(), page.getRecords());
    }

    private static <T> PageResult<T> getInstance(int code, String msg, Long total,List<T> rows){
        return new PageResult(code, msg, total, rows);
    }

    public static <T> PageResult<T> success(Long total,List<T> rows){
        return getInstance(CommonConstant.DEFAULT_SUCCESS_CODE, "SUCCESS", total, rows);
    }

    public static <T,E> PageResult<E> success(IPage<T> page,Function<List<T>, List<E>> castFunc){
        PageResult<T> pageResult = success(page.getTotal(), page.getRecords());
        return pageResult.cast(castFunc);
    }

    public static <T,E> PageResult<E> success(IPage<T> page,List<E> castList){
        return success(page.getTotal(), castList);
    }

    public <E> PageResult<E> cast(Function<List<T>, List<E>> castFunc){
        if(CollUtil.isEmpty(this.getRows())){
            return PageResult.empty();
        }
        List<E> castList = castFunc.apply(this.getRows());
        return PageResult.success(this.getTotal(),castList);
    }
}